package com.ctw.tinyservices.id.server.api;

import com.ctw.tinyservices.id.common.constants.UrlHeaderConstants;
import com.ctw.tinyservices.id.common.dto.ResponseDTO;
import com.ctw.tinyservices.id.common.dto.helper.ResponseDTOHelper;
import com.ctw.tinyservices.id.common.enums.code.ErrorCodeEnum;
import com.ctw.tinyservices.id.common.utils.LogUtils;
import com.ctw.tinyservices.id.server.token.handler.IdTokenHandler;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.LinkedList;
import java.util.List;

/**
 * @author TongWei.Chen 2022/3/31 20:27
 *
 * id api 父类
 **/
public abstract class AbstractIdApi {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private IdTokenHandler idTokenHandler;

    protected boolean canVisit(String bizType) {
        if (! idTokenHandler.canVisit(bizType, request.getHeader(UrlHeaderConstants.ID_TOKEN))) {
            LogUtils.warn(AbstractIdApi.class, "No permission to access, bizType: [{}], token is [{}]", bizType, request.getHeader(UrlHeaderConstants.ID_TOKEN));
            return false;
        }
        return true;
    }

    protected ResponseDTO<List<Long>> batchId(String bizType, int num) {
        if (! canVisit(bizType)) {
            return ResponseDTOHelper.fail(ErrorCodeEnum.AUTH_ERROR);
        }
        List<Long> ids = doBatchId(bizType, num);
        if (ids.size() == 0) {
            return ResponseDTOHelper.fail();
        }
        if (ids.size() < num) {
            return ResponseDTOHelper.fail(ErrorCodeEnum.BATCH_ERROR);
        }
        return ResponseDTOHelper.success(ids);
    }

    protected List<Long> doBatchId(String bizType, int num) {
        return new LinkedList<>();
    }
}
